<?php
namespace Plu\qdh\Controllers\Api;

use Phalcon\Mvc\Controller,
    Phalcon\Mvc\Dispatcher;

class ControllerBase extends Controller {
    const API_VERSION = '1.0';
    const FORMAT_JSON = 'json';
    const FORMAT_MSGPACK = 'msgpack';

    public function initialize() {
		
    }

	public function release($data, $noHeader = false) {
		$this->view->disable();

        if (!$noHeader) {
            $data = array(
                'apiVersion' => self::API_VERSION,
                'lastupdate' => time(),
                'data'       => $data
            );
        }

		$data = json_encode($data);
		$callback = $this->request->get('callback');
		if (!empty($callback)) {
            $data = $callback.'('.$data.')';
            $this->response->setContentType('application/x-javascript');
        } else {
            $this->response->setContentType('application/json');
        }

        //add allow access controller
        $this->response->setHeader("Access-Control-Allow-Credentials", "true");
        $this->response->setHeader("Access-Control-Allow-Origin", "*");
        $this->response->setHeader("Access-Control-Max-Age", "86400");


		$this->response->setContent($data);

		return $this->response;
	}

	public function needLogin() {
		return $this->release([
			'code' => 406,
			'msg'  => '请登录'
		]);
	}

	public function missParams() {
		return $this->release([
			'code' => 407,
			'msg'  => '参数不完整'
		]);
	}

	public function throwNotFound() {
		$this->response->setStatusCode(404, 'Not Found');

		return $this->release(array(
			'error' => 'Not Found',
			'status'=> 404,
			'message'=> 'Not found'
		));
	}


	public function throwUnauthorized() {
		$this->response->setStatusCode(401, 'Unauthorized');

		return $this->release(array(
			'error' => 'Unauthorized',
			'status'=> 401,
			'message'=> 'Token invalid or missing required scope'
		));
	}
    
}
